import fs from 'fs';
import path from 'path';
import multer from 'multer';
import { fileURLToPath } from 'url';

// 获取当前模块的目录名
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

//获取文件内容
const getFileContent = (req, res) => {
  //   获取请求的参数;
  const data = req.body;
  if (data.url) {
    // 读取 Vue 文件内容
    const vueFilePath = path.resolve(__dirname, `../../../src/views${data.url}`);
    fs.readFile(vueFilePath, 'utf-8', (err, fileData) => {
      if (err) throw err;
      res.send({
        code: 200,
        result: fileData,
      });
    });
  } else {
    res.send({
      code: 200,
      result: `请正确传参`,
    });
  }
};

//获取文件夹下子文件名称
const getSubfileName = (req, res) => {
  const data = req.body;
  if (data.folderUrl) {
    // 读取 Vue 文件内容
    const folderPath = path.resolve(__dirname, `../../../src/views${data.folderUrl}`);
    fs.readdir(folderPath, 'utf-8', (err, files) => {
      if (err) throw err;
      res.send({
        code: 200,
        result: files,
      });
    });
  } else {
    res.send({
      code: 200,
      result: `请正确传参`,
    });
  }
};

// 所有附件保存目录
const uploadFileDir = path.join(__dirname, '../../uploadFile');
// 配置 multer 存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    //创建时间戳文件夹，用于存放本次上传的所有附件
    const dateNow = new Date().getTime().toString();
    file.dateNow = dateNow;
    const newDirPath = path.join(uploadFileDir, dateNow);

    fs.mkdir(newDirPath, (err) => {
      if (err) {
        return console.error('创建目录失败:', err);
      }
      cb(null, newDirPath);
    });
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname); // 文件名格式
  },
});
// 配置 multer 存储
const multerUpload = multer({ storage: storage });

//附件上传
const fileUpload = (req, res) => {
  const fileInfo = req.file;
  res.send({
    code: 200,
    result: {
      fileId: fileInfo.dateNow,
      fileName: fileInfo.filename,
      fileAddress: fileInfo.path,
      size: fileInfo.size,
    },
  });
};

//附件删除
const fileDelete = (req, res) => {
  const data = req.body;
  if (data.fileId) {
    //删除对应文件
    fs.unlink(path.resolve(uploadFileDir, `${data.fileId}/${data.fileName}`), (err) => {
      if (err) throw err;
      res.send({
        code: 200,
        result: `删除成功`,
      });
    });
  } else {
    res.send({
      code: 200,
      result: `请正确传参`,
    });
  }
};

export default {
  getFileContent,
  getSubfileName,
  fileUpload,
  multerUpload,
  fileDelete,
};
